package com.zhugang.week05;

/**
 * @program algorithms
 * @description: searchInsert
 * @author: chanzhugang
 * @create: 2022/07/05 16:28
 */
public class SearchInsert {

    public static void main(String[] args) {
        SearchInsert searchInsert = new SearchInsert();
        int[] nums = new int[]{1, 3, 5, 6};
        int index = searchInsert.searchInsert(nums, 2);
        System.out.println(index);
    }

    /**
     * 35 搜索插入位置
     *
     * @param nums
     * @param target
     * @return
     */
    public int searchInsert(int[] nums, int target) {
        // 目标值找不到返回应该被插入的位置：转化为第一个大于等于给定值的元素位置
        int low = 0;
        int high = nums.length - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (nums[mid] >= target) {
                // 命中
                // 是否是第一个值：向前探测
                if (mid == 0 || nums[mid - 1] < target) {
                    return mid;
                } else {
                    high = mid - 1;
                }
            } else {
                // 目标值在右边
                low = mid + 1;
            }
        }
        // 特殊处理
        return nums.length;
    }
}